<template>
  <el-scrollbar ref="scrollFun">
    <div
      id="yxku"
      ref="yxkuRef"
      v-infinite-scroll="load"
      :infinite-scroll-immediate="false"
    >
      <div class="main">
        <!-- nav -->
        <div class="df curpoin nav-box">
          <div
            class="item-box"
            @click="handleNavClick('1')"
            :class="{ activenav: active === '1' }"
          >
            全部院校
          </div>
          <div
            class="item-box"
            style="margin: 0 15px"
            @click="handleNavClick('2')"
            :class="{ activenav: active === '2' }"
          >
            大学排名
          </div>
          <div
            class="item-box"
            @click="handleNavClick('3')"
            :class="{ activenav: active === '3' }"
          >
            院校对比
          </div>
        </div>
        <!-- 内容 -->
        <div class="contaier" ref="tableContainerRef">
          <!-- 全部院校 -->
          <div v-show="active == 1">
            <collegeTab
              :tabDataList="tabTagList"
              :isSearch="false"
              @handleClick="handleClick"
              @handleSearchCollegeRequestData="handleSearchCollegeRequestData"
              ref="collegeTabRef"
            />
            <div style="display: flex; justify-content: space-between">
              <div style="width: 70%">
                <div
                  class="df"
                  style="
                    position: sticky;
                    top: 0;
                    left: 0;
                    background: #fff;
                    z-index: 999;
                  "
                >
                  <div class="f14" style="margin-right: 10px">
                    共
                    <span style="color: var(--color-text)">{{ total }}</span> 条
                  </div>
                  <div class="search-box">
                    <el-popover
                      placement="bottom-start"
                      trigger="click"
                      :visible="popperVis"
                      popper-class="popoverStyle"
                    >
                      <template #reference>
                        <!-- style="width: 100%" -->
                        <el-input
                          @keyup.enter="handleTbaleSearch"
                          @focus="handleInputFocus"
                          @blur="handleInputBlur"
                          size="large"
                          clearable
                          :prefix-icon="Search"
                          v-model="searchvalue"
                          placeholder="搜索"
                        >
                          <template #append>
                            <!-- style="background: var(--background-color); color: #fff" -->
                            <el-button size="large" @click="handleTbaleSearch"
                              >搜索</el-button
                            >
                            <!-- <div class="my-btn">搜索</div> -->
                          </template>
                        </el-input>
                      </template>
                      <div style="" class="his-item curr">历史记录</div>
                      <div class="curr">
                        <div
                          class="his-item"
                          v-for="item in searchHistory"
                          :key="item"
                          @click="handleSearchClick(item)"
                        >
                          {{ item }}
                        </div>
                      </div>
                    </el-popover>
                  </div>
                </div>

                <yxkTable :yxkTableList="yxkTableList" ref="tableListRef" />
                <div
                  v-if="allDataFetched"
                  class="no-data f12"
                  style="text-align: center; color: #666; line-height: 60px"
                >
                  -暂无数据-
                </div>
              </div>
              <div class="right-hot" style="width: 300px">
                <hotList :hostDataList="hostDataList" type="2" />
              </div>
            </div>
          </div>
          <!-- 大学排名 -->
          <div v-show="active == 2" style="flex: 1">
            <div class="tags-contaier">
              <collegeRanking
                @handleFetchRankFullInfo="handleFetchRankFullInfo"
              />
              <rankingTable
                :rankingCollegeList="rankingCollegeList"
                ref="tableListRankingRef"
              />
            </div>
          </div>
          <!-- 院校对比 -->
          <div v-show="active == 3" style="flex: 1">
            <div class="tags-contaier">
              <contrastTable @handleGoSearchCollege="handleGoSearchCollege" />
            </div>
          </div>
          <!-- <div class="right-hot" style="width: 300px">
            <hotList :hostDataList="hostDataList" type="2" />
          </div> -->
        </div>
        <typePopup
          :active="active"
          @handleGoContrastTable="handleGoContrastTable"
        />
      </div>
    </div>
  </el-scrollbar>
</template>

<script setup>
const yxkuRef = ref('');
import { onMounted, ref, computed, watch } from 'vue';
import { useStore } from 'vuex';
import {
  getSearchSchool,
  getRankFullInfo,
  getHotSchool,
} from '@/api/searchColleges/searchCollege';
import { getSearchSchoolFilter } from '@/api/selectSubject/subject';
import { Search } from '@element-plus/icons-vue';

import yxkTable from '../YxkuTable';
import collegeTab from '../../../../components/CollegeTab';
import rankingTable from '../RankingTable';
import collegeRanking from '../CollegeRanking';
import contrastTable from '../ContrastTable';
import hotList from '@/components/HotList';
import typePopup from '../CompareDrawer/typePopup.vue';
import imgUrl from '@/assets/images/collegesBanner.png';
const store = useStore();
const popperVis = ref(false);
const searchHistory = ref([]);
const collegeTabRef = ref([]);
const total = ref(0);
// 院校请求数据
const collegeReqData = ref({
  page: 1,
  pageSize: 10,
});

const hostDataList = ref({
  title: '热门院校排名',
  hotList: [],
  imgUrl: imgUrl,
});
const searchvalue = ref('');
const tableContainerRef = ref('');
const active = ref('1');
const yxkTableList = ref([]);
const allDataFetched = ref(false);
const allDataFetchedRanking = ref(false);
const tableListRef = ref(null);
const tableListRankingRef = ref(null);
const tabTagList = ref({});

const handleClick = () => {};

const handleNavClick = (type) => {
  allDataFetched.value = false;
  active.value = type;
};
const requestData = ref({
  page: 1,
  pageSize: 10,
  type: '校友会',
});
// 热门学校请求数据
const hotcollegeReqData = ref({
  page: 1,
  pageSize: 10,
});
const rankingCollegeList = ref([]);

const scrollFun = ref(null);

const load = () => {
  if (active.value == 1) {
    nextPage();
  } else if (active.value == 2) {
    nextRankingPage();
  }
};

const handleSearchCollegeRequestData = ({ data }) => {
  let reqData = {
    province: data['province']
      .filter((item) => item.index != 0)
      .map((v) => v.index)
      .toString(), // 过滤掉值为"0"的元素
    categories: data['categories']
      .filter((item) => item.index != 0)
      .map((v) => v.item)
      .toString(),
    features: data['features']
      .filter((item) => item.index != 0)
      .map((v) => v.item)
      .toString(),
    natureType: data['natureType']
      .filter((item) => item.index != 0)
      .map((v) => v.index)
      .toString(),
    eduLevel: data['eduLevel']
      .filter((item) => item.index != 0)
      .map((v) => v.index)
      .toString(),
  };
  collegeReqData.value = { ...collegeReqData.value, ...reqData };
  collegeReqData.value.page = 1;
  yxkTableList.value = [];
  fetchSearchSchool();
};
const handleGoSearchCollege = (type) => {
  active.value = type;
};
const handleInputFocus = () => {
  if (searchHistory.value.length <= 0) {
    popperVis.value = false;
  } else {
    popperVis.value = true;
  }
};
const handleGoContrastTable = (activeType) => {
  active.value = activeType;
};
const handleInputBlur = () => {
  popperVis.value = false;
};
// 获取热门院校排名
const fechHotSchool = () => {
  getHotSchool(hotcollegeReqData.value).then((res) => {
    if (res.data.code == 20000) {
      res.data.data.forEach((v) => {
        v.hits = v.hits / 10000;
        v.hits = v.hits.toFixed(1);
      });
      hostDataList.value.hotList = res.data.data;
    }
  });
};
const handleFetchRankFullInfo = (item) => {
  requestData.value.type = item;
  requestData.value.page = 1;
  fetchRankFullInfo();
};

// 大学排名接口
const fetchRankFullInfo = () => {
  tableListRankingRef.value.handleRankingIsTableLoading(true);
  getRankFullInfo(requestData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        rankingCollegeList.value = res.data.data;
        handleChangeIsSelect(
          store.getters.searchCollege.selectedCollege,
          rankingCollegeList.value,
        );
        tableListRankingRef.value.handleRankingIsTableLoading(false);
      }
    })
    .catch(() => {
      tableListRankingRef.value.handleRankingIsTableLoading(false);
    });
};
// 大学排名接口滚动
const fetchRankFullInfoScroll = () => {
  tableListRankingRef.value.handleRankingIsTableLoading(true);
  getRankFullInfo(requestData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        tableListRankingRef.value.handleRankingIsTableLoading(false);
        if (res.data.data.length === 0) {
          allDataFetchedRanking.value = true; // 已请求完全部数据
          return;
        }
        rankingCollegeList.value = [
          ...rankingCollegeList.value,
          ...res.data.data,
        ];
        handleChangeIsSelect(
          store.getters.searchCollege.selectedCollege,
          rankingCollegeList.value,
        );
      }
    })
    .catch(() => {
      tableListRankingRef.value.handleRankingIsTableLoading(false);
    });
};
// 查大学筛选条件
const fetchSearchSchoolFilter = () => {
  getSearchSchoolFilter().then((res) => {
    if (res.data.code == 20000) {
      tabTagList.value = res.data.data;
    }
  });
};
const handleTbaleSearch = () => {
  collegeReqData.value.page = 1;
  collegeReqData.value.search = searchvalue.value;
  if (searchvalue.value && !searchHistory.value.includes(searchvalue.value)) {
    searchHistory.value.push(searchvalue.value);
  }
  handleTbaleSearchNoScroll();
};
const handleSearchClick = (item) => {
  collegeReqData.value.page = 1;
  collegeReqData.value.search = item;
  handleTbaleSearchNoScroll();
};
const handleTbaleSearchNoScroll = () => {
  tableListRef.value.handleTableLoading(true);
  getSearchSchool(collegeReqData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        yxkTableList.value = res.data.data;
        if (res.data.data && res.data.data.length > 0) {
          yxkTableList.value = yxkTableList.value.map((v) => {
            return {
              ...v,
              searchValue: searchvalue.value,
            };
          });
        }
        tableListRef.value.handleTableLoading(false);
        total.value = res.data.total;
        handleChangeIsSelect(
          store.getters.searchCollege.selectedCollege,
          yxkTableList.value,
        );
      }
    })
    .catch(() => {
      tableListRef.value.handleTableLoading(false);
    });
};

// 院校接口
const fetchSearchSchool = () => {
  tableListRef.value.handleTableLoading(true);
  getSearchSchool(collegeReqData.value)
    .then((res) => {
      if (res.data.code == 20000) {
        tableListRef.value.handleTableLoading(false);
        if (res.data.data.length === 0) {
          allDataFetched.value = true; // 已请求完全部数据
          tableListRef.value.handleTableLoading(false);
        } else {
          tableListRef.value.handleTableLoading(false);
        }
        yxkTableList.value = [...yxkTableList.value, ...res.data.data];
        total.value = res.data.total;
        handleChangeIsSelect(
          store.getters.searchCollege.selectedCollege,
          yxkTableList.value,
        );
      }
    })
    .catch(() => {
      tableListRef.value.handleTableLoading(false);
    });
};
const selectedCollegeData = computed(
  () => store.getters.searchCollege.selectedCollege,
);
watch(selectedCollegeData, (newVal) => {
  handleChangeIsSelect(newVal, yxkTableList.value);
  handleChangeIsSelect(newVal, rankingCollegeList.value);
});
const handleChangeIsSelect = (array1, array2) => {
  // 遍历第一组数组
  for (const item1 of array1) {
    // 获取当前项的 code 值
    const code = item1.code;

    // 在第二组数组中查找相同 code 的项
    const foundItem = array2.find((item) => item.code === code);

    if (foundItem) {
      // 找到相同的项，将 isSelect 设置为 true
      foundItem.isSelect = true;
    }
  }
  // 将第二组数组中不存在于第一组数组中的项的 isSelect 设置为 false
  for (const item2 of array2) {
    const foundInArray1 = array1.find((item) => item.code === item2.code);
    if (!foundInArray1) {
      item2.isSelect = false;
    }
  }
};
const nextRankingPage = () => {
  requestData.value.page += 1;
  fetchRankFullInfoScroll();
};
const nextPage = () => {
  collegeReqData.value.page += 1;
  fetchSearchSchool();
};

onMounted(() => {
  fetchSearchSchool();
  fetchSearchSchoolFilter();
  fetchRankFullInfo();
  fechHotSchool();
});
</script>

<style lang="scss" scoped>
#yxku {
  height: 100%;
  margin-top: 20px;
  margin-bottom: 130px;
  .nav-box {
    border-bottom: 1px solid var(--color-text);
  }
  .item-box {
    padding: 10px 30px;
    // border-radius: 4px;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  .right-hot {
    margin: 15px 0 0 40px;
  }
  .search-box {
    flex: 1;
    position: sticky;
    top: 110px;
    left: 0;
    z-index: 999;
    background: #fff;
    margin: 10px 0;
  }
}
.activenav {
  background: var(--color-text);
  color: #fff;
}
.my-btn {
  background: red;
  width: 90px;
  color: #fff;
}
.prov-item {
  width: 65px;
  text-align: center;
  // margin: 0 10px 10px 0;
  margin: 10px 7px;
}
.his-item {
  padding: 5px 0 5px 25px;
  margin: 10px 0;
  &:hover {
    background: #f3f6f9;
  }
}
:deep(.el-input-group__append) {
  width: 70px;
  background: var(--background-color);
  color: #fff;
}
</style>
<style lang="scss">
.el-popover.popoverStyle {
  padding: 0 0 !important;
  // left: 350px !important;
}
</style>
